package com.heer.gymnasium.module.coach.views;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.heer.amap.utils.ToastUtil;
import com.heer.gymnasium.R;
import com.heer.gymnasium.api.ResponseData.ApiResponse;
import com.heer.gymnasium.api.SignHelper;
import com.heer.gymnasium.api.callback.BaseCallback;
import com.heer.gymnasium.base.BaseActivity;
import com.heer.gymnasium.constant.Type;
import com.heer.gymnasium.module.coach.beans.CoachBean;
import com.heer.gymnasium.module.coach.beans.CoachResponseBean;
import com.heer.gymnasium.module.login.views.LoginActivity;
import com.heer.gymnasium.module.order.views.OrderActivity;
import com.heer.gymnasium.module.store.beans.StoreBean;
import com.heer.gymnasium.module.store.views.StoreActivity;
import com.heer.gymnasium.util.ImageUtil;
import com.heer.imagepick.DensityUtils;
import com.zhihuiyun.library.utils.L;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by zy on 2018/1/23.
 * 私教下单界面
 */

public class CoachDetailActivity extends BaseActivity {
    private final static int RES_ID_ROOT = R.layout.layout_coach_detail;


    private final static int RES_ID_HEAD = R.id.layout_coach_detail_head_iv;
    private final static int RES_ID_NAME = R.id.layout_coach_detail_name_tv;
    private final static int RES_ID_SIGN = R.id.layout_coach_detail_sign_tv;
    private final static int RES_ID_PRICE = R.id.layout_coach_detail_price_tv;
    private final static int RES_ID_DURATION = R.id.layout_coach_detail_time_tv;
    private final static int RES_ID_INTRODUCE = R.id.layout_coach_detail_introduce_tv;
    private final static int RES_ID_INTRODUCE_MORE = R.id.layout_coach_detail_introduce_more_fl;
    private final static int RES_ID_PROJECT_PANEL = R.id.layout_coach_detail_project_ll;

    private final static int RES_ID_STORE_NAME = R.id.layout_coach_detail_store_tv;
    private final static int RES_ID_STORE = R.id.layout_coach_detail_store_rl;
    private final static int RES_ID_EVALUATE = R.id.layout_coach_detail_evaluate_gv;
    private final static int RES_ID_ORDER = R.id.layout_coach_detail_order_tv;

    private final static int DRAWABLE_COLLECT = R.drawable.ic_collect;
    private final static int DRAWABLE_COLLECT_YELLOW = R.drawable.ic_collect_foucs;
    private final static int DRAWABLE_YELLOW_BORDER = R.drawable.yellow_border;

    @BindView(RES_ID_HEAD)
    ImageView ivHead;
    @BindView(RES_ID_NAME)
    TextView tvName;
    @BindView(RES_ID_SIGN)
    TextView tvSign;
    @BindView(RES_ID_PRICE)
    TextView tvPrice;
    @BindView(RES_ID_DURATION)
    TextView tvDuration;
    @BindView(RES_ID_INTRODUCE)
    TextView tvIntroduce;
    @BindView(RES_ID_PROJECT_PANEL)
    LinearLayout llProjectPanel;
    @BindView(RES_ID_STORE_NAME)
    TextView tvStoreName;
    @BindView(RES_ID_EVALUATE)
    GridView gvEvaluate;
    @BindView(RES_ID_INTRODUCE_MORE)
    View vMore;

    private CoachDetailActivity $this;
    private String id, storeId;
    private ArrayList<String> tagList;
    private ArrayAdapter<String> tagAdapter;

    private boolean canClick = true;
    private CoachResponseBean.Item itemForStartActivity;

    @Override
    protected void init() {
        super.init();
        setContentView(RES_ID_ROOT);
        $this = this;

        id = getIntent().getStringExtra(EXTRA_ID);
        if (TextUtils.isEmpty(id)) {
            ToastUtil.show($this, "未找到该教练");
            finish();
            return;
        }

        tagList = new ArrayList<>();
        tagAdapter = new ArrayAdapter<String>($this, RES_ID_ROOT, tagList) {
            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                TextView textView = new TextView($this);
                textView.setBackgroundResource(DRAWABLE_YELLOW_BORDER);
                textView.setTextColor(Color.BLACK);
                textView.setTextSize(12);
                textView.setText(tagList.get(position));
                textView.setGravity(Gravity.CENTER);
                textView.setPadding(0, 5, 0, 5);
                textView.setMaxLines(1);
                return textView;
            }
        };
    }

    @Override
    protected void initView() {
        super.initView();
        titleUtils.setRightImage(DRAWABLE_COLLECT, 15);
        gvEvaluate.setAdapter(tagAdapter);
        titleUtils.setRightOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doFocus();
            }
        });

        tvIntroduce.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (tvIntroduce.getLineCount() > 0) {
                    if (tvIntroduce.getLayout().getEllipsisCount(tvIntroduce.getLineCount() - 1) > 0) {
                        vMore.setVisibility(View.VISIBLE);
                    } else if (tvIntroduce.getMaxLines() == 3) {
                        vMore.setVisibility(View.GONE);
                    }
                }
            }
        });
    }

    @Override
    protected void loadData() {
        super.loadData();
        if (!TextUtils.isEmpty(id)) {
            getCoachDetailById(id);
        }
    }

    @OnClick(RES_ID_ORDER)
    public void onClickForOrder() {

    }

    private void getCoachDetailById(String cid) {
        mAppHelper.apiService().getCoach(cid).enqueue(new BaseCallback<ApiResponse<CoachResponseBean.Item>>() {
            @Override
            public void onSuccess(Call<ApiResponse<CoachResponseBean.Item>> call, Response<ApiResponse<CoachResponseBean.Item>> response) {
                itemForStartActivity = response.body().getData();
                initCoachInfo(CoachBean.dataChange(response.body().getData()));
                initStoreInfo(StoreBean.dataChange(response.body().getData()));
            }
        });
    }

    private void initStoreInfo(StoreBean storeBean) {
        tvStoreName.setText(storeBean.getStadiumname());
        storeId = storeBean.getSid();
    }

    private void initCoachInfo(CoachBean coachBean) {
        tvName.setText(coachBean.getCoach_name());
        tvPrice.setText(coachBean.getPrice() + "元/次");
        tvDuration.setText(coachBean.getOne_time() + "分钟");
        tvSign.setText(coachBean.getSign());
        if (coachBean.getFocus_id() == 0) {
            titleUtils.setRightImage(DRAWABLE_COLLECT, 15);
        } else {
            titleUtils.setRightImage(DRAWABLE_COLLECT_YELLOW, 15);
        }

        ImageUtil.loadUrl($this, coachBean.getAvatar(), DRAWABLE_DEFAULT_HEAD, ivHead);
        tvIntroduce.setText(coachBean.getIntr());
        llProjectPanel.removeAllViews();
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(DensityUtils.dip2px($this, 15), DensityUtils.dip2px($this, 15));
        layoutParams.setMargins(0, 0, DensityUtils.dip2px($this, 3), 0);
        for (String path : coachBean.getCategory_list()) {
            final ImageView imageView = new ImageView($this);
            Glide.with($this).load(path.replace("\\", "/")).into(imageView);
            imageView.setLayoutParams(layoutParams);
            llProjectPanel.addView(imageView);
        }

        tagList.clear();
        tagList.addAll(coachBean.getTag_list());
        tagAdapter.notifyDataSetChanged();
    }

    @OnClick({RES_ID_INTRODUCE, RES_ID_INTRODUCE_MORE})
    public void showMore() {
        if (tvIntroduce.getMaxLines() == 3) {
            tvIntroduce.setMaxLines(Integer.MAX_VALUE);

            if (vMore.getVisibility() == View.VISIBLE) {
                RotateAnimation rotateAnimation = new RotateAnimation(0.0f, +180.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                rotateAnimation.setDuration(60);
                rotateAnimation.setFillAfter(true);
                rotateAnimation.setRepeatCount(0);
                vMore.startAnimation(rotateAnimation);
            }
        } else {
            tvIntroduce.setMaxLines(3);

            if (vMore.getVisibility() == View.VISIBLE) {
                RotateAnimation rotateAnimation = new RotateAnimation(+180.0f, 0.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                rotateAnimation.setDuration(60);
                rotateAnimation.setFillAfter(true);
                rotateAnimation.setRepeatCount(0);
                vMore.startAnimation(rotateAnimation);
            }
        }
    }

    private void doFocus() {
        if (canClick) {
            canClick = false;
            mAppHelper.apiService().doFocus(FOCUS_TYPE_COACH, id).enqueue(new BaseCallback<ApiResponse<String>>() {
                @Override
                public void onSuccess(Call<ApiResponse<String>> call, Response<ApiResponse<String>> response) {
                    canClick = true;
                    ToastUtil.show($this, response.body().getMsg());
                    loadData();
                }

                @Override
                public void onTokenTimeOut() {
                    canClick = true;
                    LoginActivity.logout($this, LoginActivity.TIME_OUT);
                }

                @Override
                public void onError(Call<ApiResponse<String>> call, Throwable t) {
                    canClick = true;
                }
            });
        }
    }


    public static void startActivity(Context context, String coachId) {
        Intent mIntent = new Intent(context, CoachDetailActivity.class);
        mIntent.putExtra(EXTRA_ID, coachId);
        context.startActivity(mIntent);
    }

    @OnClick(RES_ID_STORE)
    public void toStore() {
        StoreActivity.startActivity($this, storeId);
    }

    @OnClick(RES_ID_ORDER)
    public void toOrder() {
        OrderActivity.startActivity($this, OrderActivity.OrderType.from_coach, itemForStartActivity.getCoach_id(), Type.ORDER_COACH);
    }
}
